package com.snails.ui.list;

import android.content.Context;
import android.util.SparseArray;
import android.view.View;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

/**
 * 精准计算RecyclerView滑动距离，支持item高度不同
 *
 * @author lawrence
 * @date 2019-05-28 14:34
 */
public class OffsetLinearLayoutManager extends LinearLayoutManager {

    private SparseArray<Integer> map = new SparseArray<>(15);

    public OffsetLinearLayoutManager(Context context) {
        super(context);
    }

    @Override
    public void onLayoutCompleted(RecyclerView.State state) {
        super.onLayoutCompleted(state);
        int count = getChildCount();
        for (int i = 0; i < count; i++) {
            View view = getChildAt(i);
            map.put(i, view.getHeight());
        }
    }

    @Override
    public int computeVerticalScrollOffset(RecyclerView.State state) {
        return super.computeVerticalScrollOffset(state);
//        return statisticalVerticalScrollOffset();
    }

    /**
     * 统计垂直滚动距离
     * @return
     */
    public int statisticalVerticalScrollOffset() {
        int offsetY = 0;  // 垂直偏移量
        if (getChildCount() > 0) {
            try {
                // 第一个可见item的位置（用户角度位置）
                final int firstVisiblePosition = findFirstVisibleItemPosition();
                if (firstVisiblePosition >= 0) {
                    // 得到第一个可见view
                    View firstVisibleView = findViewByPosition(firstVisiblePosition);
                    // 得到第一个可见view距离顶部的偏移量
                    if (firstVisibleView != null) offsetY = -(int) (firstVisibleView.getY());

                    for (int i = 0; i < firstVisiblePosition; i++) {
                        offsetY += map.get(i) == null ? 0 : map.get(i);
                    }
                }
            } catch (Exception e) {
                offsetY = 0;
                e.printStackTrace();
            }
        }
        return offsetY;
    }

}
